import { inlineSource as inline } from 'inline-source';
import JsReport from 'jsreport-core';
import JsreportPhantomPdf from 'jsreport-phantom-pdf';

/**
 * html转换为pdf
 * @param html 需转换的html内容
 * @param orientation 版式，横版、竖版
 * @param attachment 文件名称-可选参数
 * @example html2pdf(html, orientation, attachment, rootpath, width, height);
 */
export default async function html2pdf(html: string, orientation: 'portrait' | 'landscape', attachment?: string, rootpath = '', width?: string, height?: string) {
	const jsreport = JsReport();
	jsreport.use(JsreportPhantomPdf());
	const content = await inline(html, {
		compress: true,
		rootpath
	});
	await jsreport.init();
	const resp = await jsreport.render({
		template: {
			content,
			engine: 'none',
			phantom: {
				height,
				orientation,
				width
			},
			recipe: 'phantom-pdf'
		}
	});
	// fs.writeFileSync('./a.pdf', resp.content);
	if (attachment) {
		return {
			attachment,
			buff: resp.content,
			content_type: 'application/pdf'	// application/octet-stream
		};
	} else {
		return {
			buff: resp.content,
			content_type: 'application/pdf'
		};
	}
}
